package com.regentsoft.cloudback.interceptor;

import com.regentsoft.cloudback.base.BaseResp;
import com.regentsoft.cloudback.base.ResponseCode;
import com.regentsoft.cloudback.enterpriseAdmin.util.AdminTokenManager;
import com.regentsoft.cloudback.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 管理后台拦截器
 * Created by work on 2017/11/27.
 *
 * @author lumr
 */
public class EnterpriseInterceptor extends HandlerInterceptorAdapter{
    private final AdminTokenManager tokenManager;

    private final String TOKEN = "REGENTTOKEN";

    public EnterpriseInterceptor(AdminTokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getParameter(TOKEN);
        if (token == null) {
            respError(response);
            return false;
        }

        boolean exist =  tokenManager.exists(token);
        if (!exist){
            respError(response);
            return false;
        }
        return true;
    }

    private void respError(HttpServletResponse response) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("text/html;charset=UTF-8");
        BaseResp resp = new BaseResp();
        resp.setCode(ResponseCode.NOTLOGIN);
        resp.setMessage("尚未登录");
        PrintWriter writer = response.getWriter();
        writer.write(JsonUtil.toJsonStr(resp));
        writer.close();
    }
}
